<script setup lang="tsx">
import { computed, PropType, reactive, ref } from 'vue'
import { Dialog } from '@/components/Dialog'
import { ElForm, ElMessage, FormInstance, FormRules } from 'element-plus'
import { useDesign } from '@/hooks/web/useDesign'
import { Plus } from '@element-plus/icons-vue'
import { SelectOption } from '@/api/common/types'
import { getDictionarySelectOptionList } from '@/utils/dictionary'
import { SystemRole } from '@/api/system/role/types'
import { checkRoleNameApi, createSystemRoleApi, updateSystemRoleApi } from '@/api/system/role'

const props = defineProps({
  modelValue: {
    type: Boolean
  },
  refreshList: {
    type: Function,
    required: true
  },
  role: {
    type: Object as PropType<SystemRole>
  },
  title: {
    type: String
  },
  create: {
    type: Boolean
  }
})
const validateRoleName = (rule, value, callback) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('角色名称不能为空'))
  } else {
    checkRoleNameApi({
      roleName: value,
      roleId: systemRole.roleId
    })
      .then((res) => {
        if (res?.data) {
          callback(new Error(res?.data))
        } else {
          callback()
        }
      })
      .catch(() => {
        callback(new Error('请求异常，请联系管理员！'))
      })
  }
}
const rules = reactive<FormRules<SystemRole>>({
  roleName: [{ required: true, trigger: 'blur', validator: validateRoleName }]
})
const systemRole = reactive<SystemRole>({
  roleId: props.role?.roleId,
  roleName: props.role?.roleName,
  roleStatus: props.role?.roleStatus,
  roleDesc: props.role?.roleDesc
})
const loading = ref(false)
const emit = defineEmits(['update:modelValue'])
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  }
})
const roleFormRef = ref<FormInstance>()
const createRole = async () => {
  loading.value = true
  await roleFormRef.value?.validate(async (isValid) => {
    if (isValid) {
      const res = await createSystemRoleApi(systemRole)
      if (res?.code === 200) {
        ElMessage.success('新增成功')
        if (props.refreshList) {
          props.refreshList()
        }
        dialogVisible.value = false
      }
    }
    loading.value = false
  })
}
const updateRole = async () => {
  loading.value = true
  await roleFormRef.value?.validate(async (isValid) => {
    if (isValid) {
      const res = await updateSystemRoleApi(systemRole)
      if (res?.code === 200) {
        ElMessage.success('编辑成功')
        if (props.refreshList) {
          props.refreshList()
        }
        dialogVisible.value = false
      }
    }
    loading.value = false
  })
}

const roleStatusList = ref<SelectOption[]>()
const getDictionaryList = async () => {
  roleStatusList.value = getDictionarySelectOptionList('status')
}
getDictionaryList()
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('form')
</script>
<template>
  <div>
    <Dialog v-model="dialogVisible" :title="props.title" max-height="250px">
      <el-form
        ref="roleFormRef"
        :model="systemRole"
        :rules="rules"
        label-width="100px"
        label-position="right"
        status-icon
        :class="prefixCls"
        style="padding-right: 50px; padding-top: 10px"
      >
        <el-row>
          <el-col>
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="systemRole.roleName" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="状态" prop="roleStatus">
              <el-select v-model="systemRole.roleStatus" placeholder="请选择角色状态">
                <el-option
                  v-for="item in roleStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="角色描述" prop="introduction">
              <el-input
                v-model="systemRole.roleDesc"
                :autosize="{ minRows: 4, maxRows: 8 }"
                type="textarea"
                placeholder="请输入角色描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          :loading="loading"
          @click="props.create ? createRole() : updateRole()"
          >保存</el-button
        >
        <el-button @click="dialogVisible = false">取消</el-button>
      </template>
    </Dialog>
  </div>
</template>
